/**
 * 评分数据抓取结果显示弹窗
 * 原抖音评分数据抓取结果显示弹窗
 * 复用到淘宝和快手
 */
import { Button, Modal, Select } from "antd"
import React, { useEffect, useState } from "react"
import * as xlsx from "xlsx"

import { _callApi, getUserShopList } from "~utils/tools"

// 弹窗组件参数定义
interface DyShopScoreDataDetailModalProps {
  // 店铺类型
  shopType?: "dy" | "tb" | "ks" | "wx"
  // 键列表
  keys?: string[]
  // 数据对象
  dataObject: any
  // 完整率
  dataCompleteRate: string
  // 显示详情弹窗状态
  showDetailModal: boolean
  // 关闭触发方法
  handleClose: () => void
  // 清空数据触发方法
  handleClear: () => void
  // 捕获数据触发方法 async方法
  handleCapture: () => Promise<void>
  // 异常信息提示
  exceptionTxt: string
}

// 弹窗组件
const DyShopScoreDataDetailModal: React.FC<DyShopScoreDataDetailModalProps> = (
  props
) => {
  // 用户店铺类别名称
  const [shopTypeName, setShopTypeName] = useState("")
  // 用户店铺列表
  const [shopList, setShopList] = useState([])
  // 选择店铺id
  const [shopID, setShopID] = useState()
  // 错误信息
  const [errMsg, setErrMsg] = useState("")
  // 成功信息
  const [successMsg, setSuccessMsg] = useState("")
  // 禁用按钮状态
  const [disBtn, setDisBtn] = useState(false)
  // 提示框
  const [modal, contextHolder] = Modal.useModal()

  // 获取店铺类别名称
  useEffect(() => {
    // 过滤类型映射
    const filterMap = {
      tb: "淘宝",
      dy: "抖音",
      ks: "快手",
      wx: "视频号"
    }
    const shopType = props.shopType || "dy"
    setShopTypeName(filterMap[shopType])
  }, [])

  // 数据项显示元素
  const DataItemBlock = () => {
    const _scoreData = props.dataObject || {}
    const dataKeys = Object.keys(_scoreData)
    // 如果有键列表数据，转为对象匹配
    let keyMap = {}
    if (props.keys && props.keys.length > 0) {
      keyMap = props.keys.reduce((pre, cur) => {
        pre[cur] = cur
        return pre
      }, {})
    }
    return dataKeys.map((key, idx) => {
      let keyClass = "ssd-item-key"
      if (keyMap[key]) {
        keyClass = "ssd-item-right-key"
      } else {
        keyClass = "ssd-item-loss-key"
      }
      return (
        <div className={"ssd-item"} key={"sdItem" + idx}>
          <span className={keyClass}>{key}</span>
          <span className={"ssd-item-value"}>{_scoreData[key]}</span>
        </div>
      )
    })
  }
  // 导出数据的方法
  const exportData = async () => {
    const _scoreData = props.dataObject || {}
    if (Object.keys(_scoreData).length <= 0) return
    // 获取header数组
    const header = []
    for (let key in _scoreData) {
      header.push(key)
    }
    const data = [_scoreData]
    const wb = xlsx.utils.book_new()
    const ws = xlsx.utils.json_to_sheet(data, { header: header })
    xlsx.utils.book_append_sheet(wb, ws, "sheet1")
    xlsx.writeFile(
      wb,
      `${data[0]["店铺名称"]}_${data[0]["日期"]}_体验分数据.xlsx`
    )
  }
  const tipsTimeout = 5 * 1000
  // 更新提示错误信息
  const updateErrorTips = (msg: string) => {
    setErrMsg(msg)
    setSuccessMsg("")
    // 定时器关闭提示
    setTimeout(() => {
      setErrMsg("")
    }, tipsTimeout)
  }
  // 更新提示成功信息
  const updateSuccessTips = (msg: string) => {
    setSuccessMsg(msg)
    setErrMsg("")
    // 定时器关闭提示
    setTimeout(() => {
      setSuccessMsg("")
    }, tipsTimeout)
  }
  // 上传数据方法
  const uploadData = async () => {
    // 获取数据对象
    const _scoreData = props.dataObject || {}
    // 上传确认状态
    let confirmUpload = true
    // 检查数据是否重复
    // console.log(_scoreData)
    const { data: repeatRes } = await _callApi("checkRepeat", {
      // 店铺id
      prefix: shopID,
      // 日期
      day: _scoreData["日期"]
    })
    if (repeatRes["res"]) {
      // 数据重复提示
      confirmUpload = await modal.confirm({
        content: `【${_scoreData["日期"]}】数据重复，是否继续上传？`,
        getContainer: false
      })
    }
    if (!confirmUpload) return
    // 数据完整率不全 提示
    if (props.dataCompleteRate !== "100") {
      confirmUpload = await modal.confirm({
        content: "数据完整率不是100%,是否继续上传？",
        getContainer: false
      })
    }
    // 取消上传
    if (!confirmUpload) return
    // 开始上传数据
    setDisBtn(true)

    const params = {
      shop_id: shopID,
      // 店铺类型
      shop_type: props.shopType || "dy",
      // 字符化json
      data: JSON.stringify(_scoreData)
    }
    const { err, data } = await _callApi("uploadDssData", params)
    if (err !== "") {
      updateErrorTips(err)
    } else {
      // 清空数据
      props.handleClear()
      // 提示成功
      updateSuccessTips("数据上传成功")
    }
    setDisBtn(false)
  }
  // 处理抓取数据方法
  const handleFetchData = async () => {
    try {
      setDisBtn(true)
      await props.handleCapture()
    } catch (e) {
    } finally {
      setDisBtn(false)
    }
  }
  // 页脚区域组件
  const DataModalFooter = () => {
    return (
      <div className={"sdd-modal-footer-wrapper"}>
        <div className={"footer-left"}>
          <span>大G店铺选择</span>
          <Select
            value={shopID}
            size={"small"}
            style={{ width: 150, marginLeft: 10 }}
            getPopupContainer={(trigger) => {
              return trigger.parentNode
            }}
            placeholder={"请选择店铺"}
            disabled={disBtn}
            options={shopList}
            onChange={(value) => setShopID(value)}></Select>
        </div>
        <div className={"footer-right"}>
          <Button
            key={"data-capture"}
            size={"small"}
            disabled={disBtn}
            loading={disBtn}
            onClick={handleFetchData}>
            数据抓取
          </Button>
          <Button
            key={"data-clear"}
            size={"small"}
            onClick={props.handleClear}
            disabled={disBtn}>
            清空数据
          </Button>
          <Button
            key={"data-export"}
            size={"small"}
            onClick={exportData}
            disabled={disBtn || Number(props.dataCompleteRate) <= 0}>
            数据导出
          </Button>
          <Button
            size={"small"}
            key={"data-upload"}
            type={"primary"}
            disabled={!shopID || Number(props.dataCompleteRate) <= 0 || disBtn}
            onClick={uploadData}
          // loading={loading}
          >
            数据上传
          </Button>
        </div>
      </div>
    )
  }

  // 获取用户店铺列表
  const getUserShopListFn = async () => {
    const data = await getUserShopList()
    // 根据过滤字符过滤店铺列表，默认抖音
    const dyShopList = data
      .filter((item) => item.name.includes(shopTypeName))
      .map((item) => {
        return {
          value: item.id,
          label: item.name
        }
      })
    setShopList(dyShopList)
  }

  // 监听弹窗状态
  useEffect(() => {
    if (props.showDetailModal) {
      // 获取用户店铺列表
      getUserShopListFn().then()
    }
  }, [props.showDetailModal])

  return (
    <Modal
      key={"shop-score-data-detail-modal"}
      width={950}
      className={"shop-score-data-detail-modal-wrapper"}
      open={props.showDetailModal}
      footer={false}
      onCancel={props.handleClose}
      mask={false}
      title={`${shopTypeName}店铺商家体验分数据抓取`}
      getContainer={false}
      maskClosable={false}>
      <div>
        <div>{contextHolder}</div>
        <div>
          数据完整度: {props.dataCompleteRate || 0}%{" "}
          {Number(props.dataCompleteRate || 0) < 100 ? (
            <span className={"ssd-tips"}>
              *为保证数据完整性，尽量保证数据完整率为100%
            </span>
          ) : null}
        </div>
        <div style={{ marginTop: 5 }}>
          <span>数据获取详情</span>
          {props.exceptionTxt ? (
            <span className={"sdd-result-error-txt"}>{props.exceptionTxt}</span>
          ) : null}
        </div>
        <div className={"ssd-items-wrapper"}>
          <DataItemBlock />
        </div>
        <div className={"ssd-tips-wrapper"}>
          {errMsg ? (
            <div className={"sdd-result-error-txt"}>{errMsg}</div>
          ) : null}
          {successMsg ? (
            <div className={"sdd-result-success-txt"}>{successMsg}</div>
          ) : null}
        </div>
        <DataModalFooter />
      </div>
    </Modal>
  )
}

export default DyShopScoreDataDetailModal
